<template>
  <div class="login-container">
    <video
      data-v-73443695=""
      muted="muted"
      src="../../assets/vedio/background.mp4"
      loop="loop"
      autoplay="autoplay"
      class="video"
    ></video>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="demo-loginForm"
    >
      <h1 class="title" v-text="title"></h1>

      <i
        @click="(isErweiLogin = !isErweiLogin), (isSmsLogin = false)"
        :class="['jiaobiao', 'iconfont', jiaobiao]"
      ></i>

      <div class="common-login" v-if="!isErweiLogin && !isSmsLogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            v-model="loginForm.captcha"
            class="captcha"
            ref="captcha"
            maxlength="5"
            @keydown.native.enter="submitForm('loginForm')"
          ></el-input>
          <span class="captcha-svg" v-loading="loading"
            ><i @click="updataCaptcha" v-html="captchaSvg"></i
          ></span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
        <!-- 手机登入图标按钮 -->
        <el-form-item>
          <div class="sms">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-iphone"></use>
            </svg>
            <a
              href="javascript:;"
              @click="isSmsLogin = true"
              style="color: #fff; font-size: 16px">切换短信登入</a
            >
          </div>
        </el-form-item>
      </div>
      <!-- 二维码登入 -->
      <div class="erwei" v-else-if="isErweiLogin && !isSmsLogin">
        <div class="img" v-loading="qrLoading">
          <img :src="imgBase64Url" width="200px" alt="" />
          <i class="mask" :style="qrStyle" v-show="showQrMask" @click="getQrcode">
          </i>
        </div>
        <p>
					<svg aria-hidden="true"
						class="icon-wx">
						<use xlink:href="#icon-weixin"></use>
					</svg>
					<b v-text="qrTip"></b>
				</p>
      </div>
      <!-- 短信验证码登入 -->
      <div class="smsContainer" v-else>
        <el-form-item label="手机号">
          <el-input
            maxlength="11"
            v-model="phoneNumber"
            class="captcha phone"
          ></el-input>
          <!-- @click="sendSmsCode" -->
          <span @click="sendSmsCode"
            class="captcha-svg"
            v-text="smsRetryMsg"
            style="color: #888; line-height: 45px; text-decoration: underline"
          >
          </span>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="smsCode"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="smsSubmit">提交</el-button>
          <!-- @click="smsSubmit" -->
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
import * as api from "@/api/users";
import socketIo from "socket.io-client";
import qr from "qrcode";
import scancodeSuccessPic from "../../assets/img/scancode.png";
import invalidPic from "../../assets/img/invalidQr.png";
//映射vuex
import { mapMutations } from 'vuex';
//验证码校验
var validateCaptcha = (rule, value, callback) => {
  if (value.length !== 5) {
    callback("验证码必须是5位");
  } else {
    callback();
  }
};
//校验用户名
var validateUsername = (rule, value, callback) => {
  // 4到16位（字母，数字，下划线，减号）
  var reg = /^[a-zA-Z0-9_-]{3,16}$/;
  if (!reg.test(value)) {
    callback("由3到16位的字母，数字，下划线组成");
  } else {
    callback();
  }
};
//校验密码
var validatePassword = (rule, value, callback) => {
  if (value.length < 3) {
    callback(new Error("密码长度不能小于3位"));
  } else {
    callback();
  }
};

export default {
  name: "login",
  data() {
    return {
      smsDisabled: false,
      smsRetryMsg: "点击发送验证码", //xx秒之后重新发送提示
      smsCode: "", //短信验证码
      phoneNumber: "", //手机号
      captchaSvg: "", //验证码
      codeLoading: false, //验证码加载动画
      loading: true, //加载动画布尔值
      title: "千锋管理系统",
      qrTip: "请使用手机微信扫码登入",
      isErweiLogin: false,
      showQrMask: false, //是否显示二维码遮罩
      qrLoading: true, //加载二维码的Loading动画
      isSmsLogin: false, //短信登入
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      imgBase64Url: "", //二维码base64的图片地址
      isScanCodeSuccess: false, //是否扫码成功
      qrStyle: {
        backgroundImage: `url(${invalidPic})`,
      },
    };
  },
  computed: {
    jiaobiao() {
      return this.isErweiLogin
        ? "icon-diannaojiaobiao"
        : "icon-erweimajiaobiao";
    },
  },
  created() {
    this.updataCaptcha();
  },
  methods: {
    //映射vuex的mutation
    ...mapMutations(["SET_USERINFO"]),

    async smsSubmit(){
      let smsLoginRes = await api.smsLogin(this.smsCode);
      //判断 成功存储到本地
      let{userInfo,state,permission:{buttons},token}=smsLoginRes.data;
      if(state){
        // localStorage.setItem("myx-userInfo", JSON.stringify(userInfo));
        localStorage.setItem("myx-permissionBtn",JSON.stringify(buttons));
              localStorage.setItem("myx-token", token);
              //调用vuex，设置用户信息
                this.SET_USERINFO(userInfo);
              //跳转到欢迎页
              this.$router.push("/");
      }
    },
    //短信登入
    async sendSmsCode(){
      //判断是否可以发短信
      if(this.smsDisabled){
        this.$message.error("一分钟只能发送一次")
        return;
      }
      let smsResult=await api.getSmsCode(this.phoneNumber);
      let{state}=smsResult.data;
      if(state){
        //锁住smsDisabled
        this.smsDisabled=true;
        this.$message.success("短信发送成功");
        this.smsSecond=60;
        this.smsInterval=setInterval(()=>{
          this.smsSecond--;
          if(this.smsSecond===0){
            //情调定时器
            clearInterval(this.smsInterval);
            //文字复原
            this.smsRetryMsg="点击发送验证码";
            //解锁smsDisabled
            this.smsDisabled=false;
            return
          }
          this.smsRetryMsg=`${this.smsSecond}秒后重新发送`
        },1000)
      }
    },
    //获取二维码地址
    async getQrcode(sid) {
      this.qrTip = "请使用手机微信扫码登入";
      this.showQrMask = false;
      this.qrLoading = true;
      sid = localStorage.getItem("myx-sid") ?? sid;
      let qrResult = await api.getQrcode(sid);
      let { scanCodeUrl, state: getQrState } = qrResult.data;
      if (getQrState) {
        qr.toDataURL(scanCodeUrl, (err, imgBase64Url) => {
          if (err) {
            this, $messageBox.error(err);
            return;
          }
          this.imgBase64Url = imgBase64Url;
          this.qrLoading = false;
        });
      }
    },
    //常规登入
    async submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登入",
            spinner: "el-icon-loading",
            background: "rgba(0,0,0,0.7)",
          });
          let { username, password, captcha } = this.loginForm;
          //校验验证码
          api.verifyCaptcha(captcha).then(async (res) => {
            let { state, msg } = res.data;
            if (state) {
              //正确
              let loginRes = await api.login(username, password);
              let { state: loginState, msg, token, userInfo } = loginRes.data;
              if (loginState) {
                //登入成功 关闭加载动画
                loading.close();
                localStorage.setItem("myx-token", token);
                //调用vuex的方法,设置用户信息
                this.SET_USERINFO(userInfo);
                //跳转
                this.$router.push("/");
                //提示登陆成功
                this.$message({
                  message: msg,
                  type: "success",
                  duration: 1000,
                });
              } else {
                //登入失败 关闭动画
                loading.close();
              }
            } else {
              //验证码失败 关闭动画
              loading.close();
              this.updataCaptcha();
            }
          });
        } else {
          //验证不通过
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //获取验证码
    updataCaptcha() {
      this.loading = true;
      api.getCaptcha().then((res) => {
        // console.log(res);
        let { img } = res.data;
        this.captchaSvg = img;
        this.loading = false;
      });
    },
  },
  watch: {
    //监听短信切换登入
    isSmsLogin(val){
      //不是短信登入时清掉定时器
      if(!val){
        if(this.smsInterval){
          clearInterval(this.smsInterval);
        }
        this.smsRetryMsg="点击发送验证码"
      }
    },
    //监听二维码
    isErweiLogin(isErwei) {
      if (isErwei) {
        //打开二维码加载动画
        this.qrLoading = true;
        //需要把遮罩关掉
        this.showQrMask = false;
        let io = socketIo("wss://chst.vip");
        //扫码成功
        io.on("scancodeSuccess", async (data) => {
          //显示二维码的遮罩 并且将背景图片换成扫码成功的背景图片
          this.showQrMask = true;
          this.qrStyle.backgroundImage = `url(${scancodeSuccessPic})`;
          let { state: scanCodeState, wechatCode } = data;
          if (scanCodeState) {
            let sacnCodeRes = await api.wechatLogin(wechatCode);
            let {
              state,
              userInfo,
              permission: { buttons },
              token,
            } = sacnCodeRes.data;
            if (state) {
              localStorage.setItem("myx-userInfo", JSON.stringify(userInfo));
              localStorage.setItem(
                "myx-permissionBtn",
                JSON.stringify(buttons)
              );
              localStorage.setItem("myx-token", token);
              //调用vuex的方法,设置用户信息
								this.SET_USERINFO(userInfo);
              //跳转到欢迎页
              this.$router.push("/");
              //关闭二维码遮罩
              this.showQrMask = false;
            }
          }
        });
        //二维码失效
        io.on("invalidCode", (data) => {
          let { state } = data;
          if (!state) {
            this.showQrMask = true;
            this.qrTip = "二维码失效,请点击重新获取二维码";
          }
        });
        //连接成功
        io.on("connectSuccess", async (data) => {
          let { sid } = data;
          localStorage.setItem("myx-sid", sid);
          this.getQrcode(sid);
        });
      }
    },
  },
};
</script>
<style lang='less' scoped>
.icon-wx {
  width: 25px !important;
  height: 25px !important;
  vertical-align: -7px;
  margin-right: 3px;
}
.login-container {
  text-align: center;
  color: #fff;

  .common-login {
    padding-right: 50px;
  }

  //二维码样式
  .erwei .img {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;

    img {
      position: absolute;
      left: 0;
    }

    .mask {
      width: 100%;
      height: 100%;
      opacity: 0.8;
      background-color: #fff;
      position: absolute;
      left: 0;
      // background-image: url("../../assets/img/scancode.png");
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: center;
      cursor: pointer;
    }
  }

  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: -1px;
    top: -1px;
    cursor: pointer;
    opacity: 0.7;
  }

  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }

  .bg2 {
    background-image: url("../../assets/img/bg2.png");
    background-repeat: no-repeat;
    position: fixed;
    width: 20%;
    height: 40%;
    background-size: 100% 100%;
    left: 20%;
    top: 40%;
    opacity: 0.5;
  }

  .el-form {
    position: fixed;
    right: 10%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 100px 0 50px 0;

    /deep/ .el-input__inner {
      width: 250px;
    }

    /deep/ .el-button--primary {
      background: linear-gradient(90deg, #1596fb, #002dff);
      width: 250px;
    }

    /deep/ .el-form-item__label {
      color: #fff;
    }

    .title {
      margin: 0 0 60px 0;
      text-align: center;
      color: #fff;
    }

    /deep/ .captcha {
      width: 100px;
      vertical-align: top;

      .el-input__inner {
        width: 100%;
        height: 45px;
        border-radius: 5px 0 0 5px;
        border: 0;
        font-size: 18px;
      }
    }

    svg path {
      stroke: red;
    }

    .captcha-svg {
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 150px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }

    .el-form-item__content {
      margin-left: 30px !important;
      width: 250px !important;
    }
  }
}

.sms {
  margin-left: -15px !important;
  width: 250px !important;
}

.smsContainer {
  padding-right: 20px !important;
  width: 89%;

  /deep/ .el-form-item__label {
    // margin-left: 80px !important
    padding: 0 !important;
    padding-right: 10px !important;
  }

  /deep/ .phone {
    width: 140px !important;
  }

  /deep/ .captcha-svg {
    width: 115px !important;
  }

  /deep/ .el-form-item__content {
    margin: 0;
  }
}
</style>